<?php

namespace App\Services;

use App\Models\UserLog;
use common\utils\SysCode;
use common\enum\UserLogEnum;

//帮助公告service
class UserLogService
{
    public static $validColumn = ['user_id', 'username', 'type', 'type_name', 'device'];

    public static function create($attrs)
    {
        // 过滤字段
        foreach ($attrs as $k => $v) {
            if (!in_array($k, self::$validColumn)) {
                error_exit(SysCode::INVALID_ARGUMENT);
            }
        }
        if (isset($attrs['type'])) {
            $attrs['type_name'] = UserLogEnum::$userOpTypes[$attrs['type']];
        }
        $attrs['ip'] = self::getIp();
        if (!isset($attrs['domain'])) {
            $attrs['domain'] = $_SERVER['SERVER_NAME'];
        }
        return UserLog::insert($attrs);
    }

    protected static function getIp()
    {
        if (isset($_SERVER['HTTP_X_REAL_IP'])) {
            return $_SERVER['HTTP_X_REAL_IP'];
        }
        $onlineip = 'Unknown';
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
            $real_ip = $ips['0'];
            if ($_SERVER['HTTP_X_FORWARDED_FOR'] && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $real_ip)) {
                $onlineip = $real_ip;
            } elseif ($_SERVER['HTTP_CLIENT_IP'] && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
                $onlineip = $_SERVER['HTTP_CLIENT_IP'];
            }
        }
        if ($onlineip == 'Unknown' && isset($_SERVER['HTTP_CDN_SRC_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CDN_SRC_IP'])) {
            $onlineip = $_SERVER['HTTP_CDN_SRC_IP'];
        }
        if ($onlineip == 'Unknown' && isset($_SERVER['HTTP_NS_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER ['HTTP_NS_IP'])) {
            $onlineip = $_SERVER ['HTTP_NS_IP'];
        }
        if ($onlineip == 'Unknown' && isset($_SERVER['REMOTE_ADDR']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['REMOTE_ADDR'])) {
            $onlineip = $_SERVER['REMOTE_ADDR'];
        }

        return $onlineip;
    }
}
